import Express from 'express'
import {IncomingMessage, ServerResponse} from "http";
import {preNormalize} from 'xcrontab/lib/pre_normize'
import {normalize} from 'xcrontab/lib/normalize'
import {Iterator, format} from 'xcrontab/lib/nextDate'
import cors from 'cors'

const app = Express()

app.use(cors())

app.get('/', (req, res) => {
    const crontab = req.query.crontab

    const normal = normalize(preNormalize(crontab))

    const from = new Date()

    if (normal.errors && normal.errors.length > 0) {
        return res.json({crontab, nextDates: [], errors: normal.errors})
    }

    const iter = new Iterator(normal, from)
    const nextDates = []
    for (let i = 0; i < 5; i++) {
        nextDates.push(format(iter.next(), true))
    }

    res.json({crontab, nextDates})
})

export default (req: IncomingMessage, res: ServerResponse) => {
    app(req, res)
}
